import hre from "hardhat";
import fs from 'fs';

const { ethers } = hre;

async function main() {
    console.log("🌉 跨链拍卖交互演示\n");

    const [deployer, user1, user2] = await ethers.getSigners();
    console.log("👤 操作账户:", deployer.address);
    console.log("👤 用户1:", user1.address);
    console.log("👤 用户2:", user2.address);

    // 从部署文件读取合约地址（或使用硬编码地址）
    let contractAddress, nftAddress, routerAddress;

    // 尝试从最新的部署文件读取
    try {
        const deploymentFiles = fs.readdirSync('deployments').filter(f => f.startsWith('crosschain-'));

        if (deploymentFiles.length > 0) {
            const latestFile = deploymentFiles.sort().reverse()[0];
            const deployment = JSON.parse(fs.readFileSync(`deployments/${latestFile}`, 'utf8'));

            contractAddress = deployment.contracts.SimpleCrossChainAuction;
            nftAddress = deployment.contracts.TestNFT;
            routerAddress = deployment.contracts.CCIPRouter;

            console.log("📋 从部署文件读取合约地址:");
            console.log("   CrossChainAuction:", contractAddress);
            console.log("   TestNFT:", nftAddress);
            console.log("   Router:", routerAddress);
        }
    } catch (error) {
        console.log("⚠️  无法读取部署文件，请手动输入合约地址");
        process.exit(1);
    }

    // 连接到合约
    const CrossChainAuction = await ethers.getContractFactory("SimpleCrossChainAuction");
    const crossChainAuction = CrossChainAuction.attach(contractAddress);

    const TestNFT = await ethers.getContractFactory("MockERC721");
    const testNFT = TestNFT.attach(nftAddress);

    console.log("\n🔍 查询当前拍卖状态...");

    try {
        // 查询拍卖状态
        const [isActive, isEnded, isSettled, timeRemaining, highestBidAmount] =
            await crossChainAuction.getAuctionStatus();

        console.log("📊 拍卖状态:");
        console.log("   活跃:", isActive);
        console.log("   结束:", isEnded);
        console.log("   已结算:", isSettled);
        console.log("   剩余时间:", timeRemaining.toString(), "秒");
        console.log("   最高出价:", ethers.formatEther(highestBidAmount), "ETH");

        // 查询拍卖信息
        const auctionInfo = await crossChainAuction.auctionInfo();
        console.log("\n📋 拍卖信息:");
        console.log("   NFT合约:", auctionInfo.nftContract);
        console.log("   Token ID:", auctionInfo.tokenId.toString());
        console.log("   卖家:", auctionInfo.seller);
        console.log("   起始价格:", ethers.formatEther(auctionInfo.startPrice), "ETH");
        console.log("   结束时间:", new Date(Number(auctionInfo.endTime) * 1000).toLocaleString());

        // 查询跨链出价数量
        const bidsCount = await crossChainAuction.getCrossChainBidsCount();
        console.log("\n🌉 跨链出价统计:");
        console.log("   总出价数:", bidsCount.toString());

        if (bidsCount > 0) {
            console.log("   出价历史:");
            for (let i = 0; i < bidsCount; i++) {
                const bid = await crossChainAuction.crossChainBids(i);
                console.log(`   ${i + 1}. 出价者: ${bid.bidder}`);
                console.log(`      金额: ${ethers.formatEther(bid.amount)} ETH`);
                console.log(`      来源链: ${bid.sourceChain}`);
                console.log(`      时间: ${new Date(Number(bid.timestamp) * 1000).toLocaleString()}`);
            }
        }

        // 查询支持的链
        console.log("\n🔗 支持的区块链:");
        const chains = [
            { name: "Ethereum Sepolia", selector: "5009297550715157269" },
            { name: "Polygon Mumbai", selector: "4051577828743386545" },
            { name: "Avalanche Fuji", selector: "6433500567565415381" }
        ];

        for (const chain of chains) {
            const isSupported = await crossChainAuction.isChainSupported(chain.selector);
            console.log(`   ${isSupported ? "✅" : "❌"} ${chain.name}`);
        }

        // 演示功能（如果拍卖仍在进行）
        if (isActive && !isEnded) {
            console.log("\n🎯 演示跨链出价功能...");

            // 模拟跨链出价
            await simulateCrossChainBid(crossChainAuction, routerAddress, user1.address, "1.5");
            await simulateCrossChainBid(crossChainAuction, routerAddress, user2.address, "2.0");

            // 查询更新后的状态
            const [, , , , newHighestBid] = await crossChainAuction.getAuctionStatus();
            console.log("📈 新的最高出价:", ethers.formatEther(newHighestBid), "ETH");
        }

        // 管理功能演示（仅所有者）
        if (deployer.address === await crossChainAuction.owner()) {
            console.log("\n👑 所有者功能演示...");

            // 添加新的支持链（示例）
            const newChainSelector = "1234567890123456789";
            console.log("🔗 添加新的支持链:", newChainSelector);

            try {
                const tx = await crossChainAuction.addSupportedChain(newChainSelector);
                await tx.wait();
                console.log("✅ 新链添加成功");

                // 移除刚添加的链
                const removeTx = await crossChainAuction.removeSupportedChain(newChainSelector);
                await removeTx.wait();
                console.log("✅ 链移除成功");
            } catch (error) {
                console.log("⚠️  链管理操作失败:", error.message);
            }
        }

        // 如果拍卖已结束但未结算，可以结算
        if (isEnded && !isSettled && deployer.address === await crossChainAuction.owner()) {
            console.log("\n🏁 拍卖已结束，进行结算...");

            try {
                const settleTx = await crossChainAuction.settleAuction();
                await settleTx.wait();
                console.log("✅ 拍卖结算成功");
            } catch (error) {
                console.log("⚠️  结算失败:", error.message);
            }
        }

    } catch (error) {
        console.error("❌ 交互过程出错:", error);
    }

    console.log("\n" + "=".repeat(50));
    console.log("🎉 跨链拍卖交互演示完成");
    console.log("=".repeat(50));
}

/**
 * 模拟跨链出价
 */
async function simulateCrossChainBid(crossChainAuction, routerAddress, bidder, ethAmount) {
    try {
        console.log(`\n🌉 模拟来自 ${bidder} 的跨链出价: ${ethAmount} ETH`);

        // 连接到模拟路由器
        const MockRouter = await ethers.getContractFactory("MockCCIPRouter");
        const mockRouter = MockRouter.attach(routerAddress);

        // 构造CCIP消息
        const bidAmount = ethers.parseEther(ethAmount);
        const messageData = ethers.AbiCoder.defaultAbiCoder().encode(
            ["address", "uint256"],
            [bidder, bidAmount]
        );

        const ccipMessage = {
            messageId: ethers.keccak256(ethers.randomBytes(32)),
            sourceChainSelector: "5009297550715157269", // Ethereum Sepolia
            sender: ethers.AbiCoder.defaultAbiCoder().encode(["address"], [bidder]),
            data: messageData,
            destTokenAmounts: []
        };

        // 发送模拟CCIP消息
        const tx = await mockRouter.simulateCCIPReceive(crossChainAuction.target, ccipMessage);
        await tx.wait();

        console.log("✅ 跨链出价处理成功");

    } catch (error) {
        console.log("⚠️  跨链出价失败:", error.message);
    }
}

/**
 * 实际跨链出价（在真实网络上使用）
 */
async function sendRealCrossChainBid(routerAddress, destinationChain, auctionAddress, bidder, amount) {
    console.log(`🌉 发送真实跨链出价到链 ${destinationChain}`);

    const IRouterClient = await ethers.getContractFactory("IRouterClient");
    const router = IRouterClient.attach(routerAddress);

    // 构造跨链消息
    const messageData = ethers.AbiCoder.defaultAbiCoder().encode(
        ["address", "uint256"],
        [bidder, ethers.parseEther(amount)]
    );

    const message = {
        receiver: ethers.AbiCoder.defaultAbiCoder().encode(["address"], [auctionAddress]),
        data: messageData,
        tokenAmounts: [],
        extraArgs: "0x",
        feeToken: ethers.ZeroAddress // 使用native token支付费用
    };

    // 计算费用
    const fee = await router.getFee(destinationChain, message);
    console.log("💰 跨链费用:", ethers.formatEther(fee), "ETH");

    // 发送消息
    const tx = await router.ccipSend(destinationChain, message, { value: fee });
    const receipt = await tx.wait();

    console.log("✅ 跨链消息已发送，交易哈希:", receipt.hash);
    return receipt;
}

// 运行交互脚本
main()
    .then(() => {
        console.log("\n🎊 交互完成");
        process.exit(0);
    })
    .catch((error) => {
        console.error("💥 交互失败:", error);
        process.exit(1);
    });
